<template>
  <div class="purchase-order">
    <el-card>
      <!-- 搜索栏 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="订单编号">
          <el-input v-model="searchForm.orderNo" placeholder="请输入订单编号" />
        </el-form-item>
        <el-form-item label="供应商">
          <el-select v-model="searchForm.supplierId" placeholder="请选择供应商">
            <el-option label="供应商A" value="1" />
            <el-option label="供应商B" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态">
            <el-option label="待审核" value="pending" />
            <el-option label="已审核" value="approved" />
            <el-option label="已完成" value="completed" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 工具栏 -->
      <div class="toolbar">
        <el-button type="primary" @click="handleAdd">新增采购单</el-button>
      </div>

      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="tableData"
      >
        <el-table-column prop="orderNo" label="订单编号" width="180" />
        <el-table-column prop="supplierName" label="供应商" width="180" />
        <el-table-column prop="totalAmount" label="总金额" width="120">
          <template #default="{ row }">
            ¥{{ row.totalAmount }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column prop="remark" label="备注" />
        <el-table-column label="操作" fixed="right" width="250">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleView(row)">查看</el-button>
            <el-button 
              v-if="row.status === 'pending'" 
              link 
              type="primary" 
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button 
              v-if="row.status === 'pending'" 
              link 
              type="success" 
              @click="handleApprove(row)"
            >
              审核
            </el-button>
            <el-button 
              v-if="row.status === 'approved'" 
              link 
              type="warning" 
              @click="handleComplete(row)"
            >
              完成
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增采购单' : '编辑采购单'"
      width="800px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="供应商" prop="supplierId">
          <el-select v-model="form.supplierId" placeholder="请选择供应商">
            <el-option label="供应商A" value="1" />
            <el-option label="供应商B" value="2" />
          </el-select>
        </el-form-item>
        
        <!-- 药品列表 -->
        <el-form-item label="药品列表">
          <el-button type="primary" @click="handleAddMedicine">添加药品</el-button>
          <el-table :data="form.medicines" class="medicine-table">
            <el-table-column label="药品名称" width="200">
              <template #default="{ row }">
                <el-select v-model="row.medicineId" placeholder="请选择药品">
                  <el-option label="阿莫西林胶囊" value="1" />
                  <el-option label="布洛芬片" value="2" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="数量" width="150">
              <template #default="{ row }">
                <el-input-number v-model="row.quantity" :min="1" />
              </template>
            </el-table-column>
            <el-table-column label="单价" width="150">
              <template #default="{ row }">
                <el-input-number v-model="row.price" :precision="2" :step="0.1" />
              </template>
            </el-table-column>
            <el-table-column label="金额" width="150">
              <template #default="{ row }">
                ¥{{ (row.quantity * row.price).toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100">
              <template #default="{ $index }">
                <el-button link type="danger" @click="handleRemoveMedicine($index)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'

// 搜索表单
const searchForm = reactive({
  orderNo: '',
  supplierId: '',
  status: ''
})

// 表格数据
const loading = ref(false)
const tableData = ref([
  {
    orderNo: 'PO202403180001',
    supplierName: '供应商A',
    totalAmount: 15800.00,
    status: 'pending',
    createTime: '2024-03-18 10:00:00',
    remark: '常规采购'
  }
])

// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(100)

// 对话框
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref<FormInstance>()
const form = reactive({
  supplierId: '',
  medicines: [] as any[],
  remark: ''
})

// 表单验证规则
const rules = {
  supplierId: [{ required: true, message: '请选择供应商', trigger: 'change' }]
}

// 获取状态类型
const getStatusType = (status: string) => {
  const map: Record<string, string> = {
    pending: 'warning',
    approved: 'success',
    completed: 'info'
  }
  return map[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const map: Record<string, string> = {
    pending: '待审核',
    approved: '已审核',
    completed: '已完成'
  }
  return map[status] || '未知'
}

// 搜索
const handleSearch = () => {
  // TODO: 实现搜索逻辑
  console.log('search:', searchForm)
}

// 重置搜索
const resetSearch = () => {
  searchForm.orderNo = ''
  searchForm.supplierId = ''
  searchForm.status = ''
  handleSearch()
}

// 新增
const handleAdd = () => {
  dialogType.value = 'add'
  dialogVisible.value = true
  // 重置表单
  form.supplierId = ''
  form.medicines = []
  form.remark = ''
}

// 编辑
const handleEdit = (row: any) => {
  dialogType.value = 'edit'
  dialogVisible.value = true
  // TODO: 获取详细数据并填充表单
}

// 查看
const handleView = (row: any) => {
  // TODO: 实现查看逻辑
  console.log('view:', row)
}

// 审核
const handleApprove = (row: any) => {
  ElMessageBox.confirm(
    `确定要审核通过采购单 ${row.orderNo} 吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // TODO: 实现审核逻辑
    ElMessage.success('审核成功')
  })
}

// 完成
const handleComplete = (row: any) => {
  ElMessageBox.confirm(
    `确定要将采购单 ${row.orderNo} 标记为已完成吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // TODO: 实现完成逻辑
    ElMessage.success('操作成功')
  })
}

// 添加药品
const handleAddMedicine = () => {
  form.medicines.push({
    medicineId: '',
    quantity: 1,
    price: 0
  })
}

// 删除药品
const handleRemoveMedicine = (index: number) => {
  form.medicines.splice(index, 1)
}

// 表单提交
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate((valid) => {
    if (valid) {
      // TODO: 实现提交逻辑
      ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功')
      dialogVisible.value = false
    }
  })
}

// 分页大小变化
const handleSizeChange = (val: number) => {
  pageSize.value = val
  handleSearch()
}

// 页码变化
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  handleSearch()
}
</script>

<style scoped>
.purchase-order {
  padding: 20px;
}
.search-form {
  margin-bottom: 20px;
}
.toolbar {
  margin-bottom: 20px;
}
.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
.medicine-table {
  margin-top: 10px;
}
</style> 